﻿using System;
using System.Collections.Generic;


namespace YummyGame.Framework
{
    public class SkillRootAction:SkillAction
    {
        private List<SkillAction> m_actions;
        private List<SkillAction> m_wait;
        private List<SkillAction> m_remove;
        private int finishCount = 0;

        public SkillRootAction()
        {
            m_actions = new List<SkillAction>();
            m_wait = new List<SkillAction>();
            m_remove = new List<SkillAction>();
        }

        public void AddChild(SkillAction child)
        {
            m_actions.Add(child);
        }

        public override void Reactive()
        {
            m_wait.Clear();
            m_remove.Clear();
            m_actions.Clear();
            finishCount = 0;

            SkillRootPrototype prototype = Prototype as SkillRootPrototype;
            foreach (var action in prototype.m_actions)
            {
                if (action != null) AddChild(action.ToRuntime(Executer));
            }
        }

        public override ActionRunState Excute()
        {
            foreach (var action in m_actions)
            {
                ActionRunState state = action.Excute();
                if (state == ActionRunState.Success) finishCount++;
                else if (state == ActionRunState.Failure) return ActionRunState.Failure;
                else
                {
                    m_wait.Add(action);
                }
            }
            if (finishCount == m_actions.Count) return ActionRunState.Success;
            return ActionRunState.Running;
        }

        public override ActionRunState Run()
        {
            foreach (var wait in m_wait)
            {
                ActionRunState state = wait.Run();
                if (state == ActionRunState.Failure) return ActionRunState.Failure;
                else if (state == ActionRunState.Success)
                {
                    m_remove.Add(wait);
                    finishCount++;
                }
            }
            foreach (var r in m_remove)
            {
                m_wait.Remove(r);
            }
            m_remove.Clear();

            if (finishCount == m_actions.Count) return ActionRunState.Success;
            return ActionRunState.Running;
        }

        public override void Dispose()
        {
            Pools.GetSkillRuntime<SkillRootAction>().Recover(this);
        }
    }
}
